#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<string.h>
#include<errno.h>
#include<arpa/inet.h>

//const int Port = 8888;
const int Port = 12345;
//const int Port = 11005;

int main(void) {
    char sendbuf[1024], recvbuf[1024];

    // 1. create socket
    int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(sock_fd == -1) {
        printf("%s\n",strerror(errno));
        return 0;
    }

    // 2. connect server IP port
    struct sockaddr_in server_addr;
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(Port);

    inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr.s_addr);

    //server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    int tmp = connect(sock_fd, (struct sockaddr *)(&server_addr),
                      sizeof(struct sockaddr));//连接服务端socket
    if(tmp == -1) {
        // printf("%s\n",strerror(errno));
        perror("connect");
        return 0;
    }

    while(1) {
        fgets(sendbuf, sizeof(sendbuf), stdin);

        send(sock_fd, sendbuf, strlen(sendbuf), 0);
        if(strcmp(sendbuf, "exit\n") == 0)
            break;
        recv(sock_fd, recvbuf, sizeof(recvbuf), 0);

        // fputs(recvbuf, stdout);
        memset(sendbuf, 0, sizeof(sendbuf));
        memset(recvbuf, 0, sizeof(recvbuf));

        usleep(1000);
    }
    close(sock_fd);
    return 0;
}
